package net.guerlab.smart.wx.internal.controller.inside;

import io.swagger.annotations.ApiParam;
import net.guerlab.commons.collection.CollectionUtil;
import net.guerlab.smart.platform.commons.util.BeanConvertUtils;
import net.guerlab.smart.wx.core.domain.WxUserDTO;
import net.guerlab.smart.wx.core.exception.WxUserInvalidException;
import net.guerlab.smart.wx.core.searchparams.WxUserSearchParams;
import net.guerlab.smart.wx.service.entity.WxUser;
import net.guerlab.smart.wx.service.service.WxUserService;
import net.guerlab.web.result.ListObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Collection;
import java.util.Collections;
import java.util.Map;

/**
 * 微信用户
 *
 * @author guer
 */
@RestController("/inside/wxUser")
@RequestMapping("/inside/wxUser")
public class WxUserController {

    private WxUserService service;

    @GetMapping("/{appId}/{openId}")
    public WxUserDTO findOne(@ApiParam(value = "appId", required = true) @PathVariable String appId,
            @ApiParam(value = "openId", required = true) @PathVariable String openId) {
        WxUser wxUser = service.findUser(appId, openId);

        if (wxUser == null) {
            throw new WxUserInvalidException();
        }

        return wxUser.toDTO();
    }

    @PostMapping
    public ListObject<WxUserDTO> findList(@RequestBody WxUserSearchParams searchParams) {
        return BeanConvertUtils.toListObject(service.queryPage(searchParams));
    }

    @PostMapping("/all")
    public Collection<WxUserDTO> findAll(@RequestBody WxUserSearchParams searchParams) {
        return BeanConvertUtils.toList(service.queryAll(searchParams));
    }

    @PostMapping("/findMap")
    public Map<String, WxUserDTO> findMap(@RequestBody Collection<String> openIds) {
        if (openIds == null || openIds.isEmpty()) {
            return Collections.emptyMap();
        }

        WxUserSearchParams searchParams = new WxUserSearchParams();
        searchParams.setOpenIds(openIds);

        Collection<WxUser> wxUsers = service.selectAll(searchParams);

        return CollectionUtil.toMap(wxUsers, WxUser::getOpenId, WxUser::toDTO);
    }

    @PostMapping("/count")
    public int findCount(WxUserSearchParams searchParams) {
        return service.selectCount(searchParams);
    }

    @Autowired
    public void setService(WxUserService service) {
        this.service = service;
    }
}
